<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\notice;

use app\model\NoticeLogModel;

trait NoticeLogTrait
{
    /**
     * 返回日志状态.
     */
    protected function getLogStatus(): int
    {
        return $this->isSendSuccess() ? NoticeLogModel::STATUS_SUCCESS : NoticeLogModel::STATUS_FAIL;
    }

    /**
     * 保存发送日志.
     */
    protected function setNoticeLog(): bool
    {
        $model = new NoticeLogModel();
        $model->setAttrs([
            'request_content' => $this->getReqContent(),
            'receive_staff_ids' => $this->getStaffs(),
            'date' => date('Ymd'),
            'hour' => date('H'),
            'status' => $this->getLogStatus(),
            'type' => $this->noticeType,
            'response_content' => $this->getRepContent(),
        ]);
        if (! $model->save()) {
            return self::setError('notice日志记录失败');
        }
        return true;
    }

    /**
     * 获取请求内容.
     * @return false|string
     */
    protected function getReqContent()
    {
        return empty($this->req) ? json_encode([]) : json_encode($this->req);
    }

    /**
     * 获取应答内容.
     * @return false|string
     */
    protected function getRepContent()
    {
        return empty($this->rep) ? json_encode([]) : json_encode($this->rep);
    }

    /**
     * 获取发送用户.
     * @return false|string
     */
    protected function getStaffs()
    {
        return empty($this->staffs) ? json_encode([]) : json_encode($this->staffs);
    }
}
